﻿using NightskyMimic.Domain;
using System.Collections.Generic;
using System.Linq;

namespace NightskyMimic.Core
{
    public class AlphaBeta : MinMax
    {
        internal override List<Action> bestActions(State root, bool isAttack)
        {
            State max = new MaxState();
            State min = new MinState();
            State result = backtracking(alphaState(root, min, max));

            result.Attack.ForEach(x => x.Resolved = false);
            result.Block.ForEach(x => x.Resolved = false);

            return isAttack ? result.Attack.Select(x => x as Action).ToList() : result.Block.Select(x => x as Action).ToList();
        }

        private State alphaState(State state, State alpha, State beta)
        {
            if (state.Depth == Parameters.TurnsForward || state.isTerminal)
                return state;

            State v = new MinState();
            List<State> children = childStates(state, true);
            foreach (State child in children) 
            {
                v = max(v, betaState(child, alpha, beta));
                if (v.Utility >= beta.Utility)
                    return v;

                alpha = max(alpha, v);
            }

            return v;
        }

        private State betaState(State state, State alpha, State beta)
        {
            if (state.Depth == Parameters.TurnsForward || state.isTerminal)
                return state;

            State v = new MaxState();
            List<State> children = childStates(state, false);
            foreach (State child in children) 
            {
                v = min(v, alphaState(child, alpha,  beta));
                if (v.Utility <= alpha.Utility)
                    return v;

                beta = min(beta, v);
            }

            return v;
        }
    }
}